#pragma once
#include "thread.h"
#include <windows.h>

DWORD WINAPI thread_process(void* derivedThread );

cheetah_thread* cheetah_thread_create(uint32 thread_index, thread_frame_func frame_func, uint32 frame_interval) {
	cheetah_thread* thread = (cheetah_thread*)malloc(sizeof(cheetah_thread));
	thread->round_interval_ = 10000;
	thread->round_tick_time_ = 0;
	thread->round_work_time_ = 0;
	thread->tick_interval_ = frame_interval;
	thread->state_ = THREAD_STATE_INIT;
	thread->work_state_ = THREAD_WORKSTATE_SUSPEND;
	thread->thread_id_ = -1;
	thread->thread_index_;
	thread->frame_func_ = frame_func;
#ifdef __CHEETAH_WIN32__
	thread->handle_ = 0;
#endif
	thread->thread_index_ = thread_index;
	return thread;
}

int32 cheetah_thread_join(cheetah_thread* thread) {
	int32 ret = WaitForSingleObjectEx(thread->handle_, INFINITE, 1);
	if (WAIT_OBJECT_0 == ret)
	{
		return 1;
	}
	return 0;
}

int32 cheetah_thread_start(cheetah_thread* thread) {
	thread->handle_ = CreateThread(NULL, 0, thread_process, thread, 0, &thread->thread_id_);
	thread->state_ = THREAD_STATE_RUNNING;
	return 1;
}

int32 cheetah_thread_stop(cheetah_thread* thread) {
	thread->state_ = THREAD_STATE_TOEXIT;
	return 1;
}

int32 cheetah_thread_pause(cheetah_thread* thread) {
	return 1;
}

int32 cheetah_thread_resume(cheetah_thread* thread) {
	return 1;
}

DWORD WINAPI thread_process(void* param) {
	cheetah_thread* thread = (cheetah_thread*)param;
	while (1)
	{
		if (thread->state_ == THREAD_STATE_RUNNING) {
			thread->frame_func_(thread->thread_index_);
		} 
		else if (thread->state_ == THREAD_STATE_TOPAUSE) {
			thread->state_ = THREAD_STATE_PAUSE;
		}
		else if (thread->state_ == THREAD_STATE_TOEXIT) {
			thread->state_ = THREAD_STATE_EXIT;
			break;
		}
		else {
			assert(0);
		}
		Sleep(thread->tick_interval_);
	}
	cheetah_thread_join(thread->handle_);
	CloseHandle(thread->handle_);
	return 0;
}
